package com.wh.service.impl;

import com.wh.beans.model.ColumnModel;
import com.wh.beans.model.TableModel;
import com.wh.dao.BaseDao;
import com.wh.dao.ext.BuilderTableColumnDao;
import com.wh.dao.ext.BuilderTableDao;
import com.wh.model.BaseModel;
import com.wh.model.BuilderTable;
import com.wh.model.BuilderTableColumn;
import com.wh.service.IExt.IBuilderTableService;
import com.legend.utils.*;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/*
*author:徐洪昌
*blog:http://cnblogs.com/xusir
*datetime:2014-07-03 20:58:25
*/
public class BuilderTableService extends BaseServiceImp implements IBuilderTableService {

    Logger log = Logger.getRootLogger();

    private BuilderTableService() {
    }

    //volatile修饰的写变量不能和之前的读写代码调整，读变量不能和之后的读写代码调整
    private volatile static IBuilderTableService instance = null;

    /**
     * 单例
     *
     * @return
     */
    public static IBuilderTableService getInstance() {
        if (instance == null) {
            synchronized (IBuilderTableService.class) {
                if (instance == null) {
                    instance = new BuilderTableService();
                }
            }
        }
        return instance;
    }

    /**
     * 批量删除数据
     */
    public ReturnResult delByIds(String ids) {
        SqlSession session = getSqlSession();
        ReturnResult result = new ReturnResult();
        try {
            BuilderTableDao dao = session.getMapper(BuilderTableDao.class);
            result = delByMap(dao, ids);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        } finally {
            session.close();
        }
        return result;
    }

    /**
     * 分页数据查询
     *
     * @param pageIndex
     * @param pageSize
     * @param map
     * @return
     */
    public ReturnResult selectByMap(int pageIndex, int pageSize, Map<String, Object> map) {
        SqlSession session = getSqlSession();
        BuilderTableDao dao = session.getMapper(BuilderTableDao.class);
        int recordNum = (pageIndex - 1) * pageSize;
        List<BuilderTable> lst = session.selectList(ConfigUtils.getInstance().getDaoPackage(".BuilderTableDao.selectByMap"), map, new RowBounds(recordNum, pageSize));
        int total = dao.count(map);
        ReturnResult result = new ReturnResult();
        result.setMsg(i18nUtils.getVal("100001000"));
        result.setRows(lst);
        result.setTotal(total);
        result.setStatus(Status.SUCCESS);
        session.close();
        return result;
    }

    @Override
    public ReturnResult insertByModel(BaseModel model) {
        SqlSession session = getSqlSession();
        BuilderTableDao dao = session.getMapper(BuilderTableDao.class);
        ReturnResult result = insertByModel(dao, model);
        session.close();
        return result;
    }

    @Override
    public ReturnResult editByModel(BaseModel model) {
        SqlSession session = getSqlSession();
        BuilderTableDao dao = session.getMapper(BuilderTableDao.class);
        ReturnResult result = editByModel(dao, model);
        session.close();
        return result;
    }

    /**
     * 根据ID获取一条数据
     *
     * @param id
     * @return
     */
    @Override
    public ReturnResult selectById(String id) {
        SqlSession session = getSqlSession();
        ReturnResult result = new ReturnResult();
        result.setStatus(Status.ERROR);
        BaseDao dao = session.getMapper(BuilderTableDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        List<BuilderTable> lst = dao.selectByMap(map);
        if (lst.size() == 1) {
            result.setData(lst.get(0));
            result.setStatus(Status.SUCCESS);
        } else {
            result.setMsg(i18nUtils.getVal("100004000"));
        }
        session.close();
        return result;
    }

    /**
     * 批量审核数据
     */
    public ReturnResult audit(int state, String[] idArr) {
        SqlSession session = getSqlSession();
        BuilderTableDao dao = session.getMapper(BuilderTableDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("idArr", idArr);
        map.put("state", state);
        Integer num = dao.audit(map);
        ReturnResult result = new ReturnResult();
        if (num > 0) {
            result.setMsg(i18nUtils.getVal("100001000"));
            result.setStatus(Status.SUCCESS);
        }
        session.close();
        return result;
    }

    /**
     * 排序
     *
     * @param sorts
     * @param ids
     * @return
     */
    public ReturnResult sort(String sorts, String ids) {
        ReturnResult result;
        SqlSession session = getSqlSession();
        BuilderTableDao dao = session.getMapper(BuilderTableDao.class);
        result = sort(session, dao, sorts, ids);
        if (session != null)
            session.close();
        return result;
    }

    @Override
    public ReturnResult selectByModel(BaseModel model) {
        SqlSession session = getSqlSession();
        BuilderTableDao dao = session.getMapper(BuilderTableDao.class);
        BuilderTable table = ((BuilderTable) model);
        List<BuilderTable> lst = dao.selectByModel(table);
        ReturnResult result = new ReturnResult();
        if (lst.size() > 0) {
            result.setStatus(Status.SUCCESS);
            result.setRows(lst);
        }
        return result;
    }

    /**
     * 生成代码
     *
     * @return
     */
    public ReturnResult makeCode(String id, String template) {
        SqlSession session = getSqlSession();
        log.info("test");
        ReturnResult result = selectById(id);
        if (result.getStatus() == Status.SUCCESS) {
            BuilderTable table = (BuilderTable) result.getData();
            BuilderTableColumnDao columnDao = session.getMapper(BuilderTableColumnDao.class);
            BuilderTableColumn column = new BuilderTableColumn();
            column.setTableName(table.getTableName());
            column.setStatus(1);
            List<BuilderTableColumn> columns = columnDao.selectByModel(column);
            TableModel tableModel = new TableModel();
            tableModel.setTableName(table.getTableName());
            tableModel.setTableRemark(table.getTableRemark());
            LinkedList cLink = new LinkedList();
            for (BuilderTableColumn c : columns) {
                ColumnModel cm = new ColumnModel();
                cm.setTableName(c.getTableName());
                cm.setColumnDatatype(StringUtils.getDataType("DbToJava",c.getColumnDatatype()));
                cm.setColumnName(c.getColumnName());
                cm.setColumnRemark(c.getColumnRemark());
                cm.setControlType(c.getControlType());
                cm.setDefaultValue(c.getDefaultValue());
                cm.setIsPrimaryKey(c.getIsPrimaryKey());
                cm.setIsRequired(c.getIsRequired());
                cm.setMaxLength(c.getMaxLength());
                cm.setMinLength(c.getMinLength());
                cm.setPlaceholder(c.getPlaceholder());
                cLink.add(cm);
            }
            if (columns.size() > 0) {
                Map map = new HashMap();
                map.put("table", tableModel);
                map.put("columns", cLink);
                map.put("sys", new MakeCodeUtils());
                Map config = new HashMap();
                config.put("package", "com.oa");//从配置里读取
                map.put("config", config);
                List<String> files = FileUtils.refreshFileList(template);
                for (String file : files) {
                    int lastIndex = file.lastIndexOf("/") + 1;
                    String templatePath = file.substring(0, lastIndex);
                    String templateName = file.substring(lastIndex);
                    int lastDotIndex = file.lastIndexOf(".");
                    String fileName = file.substring(0, lastDotIndex);
                    File tmpFile = new File(fileName);
                    if (!tmpFile.isDirectory()) {
                        fileName = fileName.replace("codetmpl", "code");
                        FreeMarkerUtils.analysisTemplate(templatePath, templateName, fileName, map);
                    }
                }

                try {
                    //String tmpPath = template.toLowerCase().replace("codetmpl", "code");
                    String src = template.toLowerCase().replace("codetmpl", "code");//指定压缩源，可以是目录或文件
                    String decompressDir = template.toLowerCase().replace("codetmpl", "codezip");//解压路径
                    String comment = "代码生成";//压缩包注释
                    ZipUtil.zip(src, decompressDir + tableModel.getTableName() + ".zip", comment);
                    result.setStatus(Status.SUCCESS);
                    result.setMsg(i18nUtils.getVal("100001000"));
                } catch (IOException e) {
                    log.error("压缩出错：" + e.getMessage());
                    result.setStatus(Status.ERROR);
                    result.setMsg(i18nUtils.getVal("100002000"));
                }
            }
        }
        session.close();
        return result;

    }
}
